package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.pojo.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sun.awt.motif.X11CNS11643;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public static void main(String[] args) throws DocumentException {
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(new Configuration());
        xmlMapperBuilder.parse(Resources.getResourceAsSteam("IOrderMapper.xml"));
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        // rootElement.selectNodes()
        List<Element> list = rootElement.selectNodes("select|update|delete|insert");
        for (Element element : list) {
            String name = element.getName();
            SqlCommandType sqlCommandType = SqlCommandType.of(name);
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();

            MappedStatement mappedStatement = new MappedStatement.Builder()
                    .id(id)
                    .resultType(resultType)
                    .paramterType(paramterType)
                    .sql(sqlText)
                    .sqlCommandType(sqlCommandType)
                    .build();

            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
            try {
                Class<?> aClass = Class.forName(namespace);
                configuration.getAllMapper().add(aClass);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }


}
